import React, { useState, useEffect } from "react"
import axios from "axios"
import { message,Button } from 'antd';
import { MD5 } from "crypto-js";
import style from "./login.module.css"
import { Input } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { Popup } from 'react-vant'
import Face from './face'
import Slider1 from './SliderPuzzleVerification'
import { Notify } from "react-vant";
import { sendSmsCode, verifySmsCode } from '../utils/aliyunSms';
// import SliderCaptcha from 'rc-slider-captcha';
// import { inRange, sleep } from 'ut2';
// import {Button} from 'antd'

import { useRef } from "react";
// import { userLogin, loginInfo } from '../../fengzhuang/Api'
import SliderCaptcha from 'rc-slider-captcha';
import { inRange, sleep } from 'ut2';
// import { Button } from 'antd'
//图片的引入
const BG_IMAGE = '/public/2.png';
const PUZZLE_IMAGE = '/public/1.png';
// 获取验证码配置
export const getCaptcha = async () => {
    return {
        bgUrl: BG_IMAGE,
        puzzleUrl: PUZZLE_IMAGE,
    };
};


function Register() {
    const [bool, setBool] = useState(false)
    //验证滑块位置
    const verifyCaptcha = async (data) => {
        await sleep();
        if (data && inRange(data.x, 80, 100)) {
            // return Promise.resolve({ verified: true },111); // 返回明确的状态对象
            setBool(true)
            return messageApi.open({
                type:"success",
                content:"验证通过"
            })
        }
        return Promise.reject(new Error("验证失败，请重试"));
    };
    const selectRef = useRef(null)
    // 用户名密码登录
    const navigate = useNavigate();
    const [form, setForm] = useState({
        username: "",
        password: "",
    })
    const [rule, setRule] = useState("")
    const [messageApi, contextHolder] = message.useMessage();

    const userRegister = async () => {

        // if(form.username >= ){
        //     console.log(21321312312);

        // }

        // await axios.post("http://localhost:3010/register",form)
        // .then(res => {
        //     if(res.data.code == 200){
        //         Notify.show({ type: 'success', message: res.data.msg })
        //         navigate("/login")
        //     }else{

        //     }
        // })

    }


    const [isshow, setIsshow] = useState("用户名密码登录")


    const [phone, setPhone] = useState('');
    const [code, setCode] = useState('');
    const [countdown, setCountdown] = useState(0);
    const [isAgreed, setIsAgreed] = useState(false);
    const [phoneError, setPhoneError] = useState('');
    const [errorMsg, setErrorMsg] = useState('');

    useEffect(() => {
        if (countdown > 0) {
            const timer = setTimeout(() => {
                setCountdown(countdown - 1);
            }, 1000);
            return () => clearTimeout(timer);
        }
    }, [countdown]);

    const handleBack = () => {
        navigate(-1);
    };

    const validatePhone = (phoneNumber) => {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phoneNumber);
    };

    const handleSendCode = async () => {
        
        if (!/^1[3-9]\d{9}$/.test(phone)) {
            setErrorMsg('手机号格式错误');
            return;
        }

        try {
            // 调用阿里云短信服务发送验证码
            const response = await sendSmsCode(phone);

            if (response.success) {
                messageApi.open({
                    type: 'success',
                    content: '验证码已发送',
                });
                // 开始60秒倒计时
                setCountdown(60);
                // 使用倒计时
                const timer = setInterval(() => {
                    setCountdown((prev) => {
                        if (prev <= 1) {
                            clearInterval(timer);
                            return 0;
                        }
                        return prev - 1;
                    });
                }, 1000);
            } else {
                setErrorMsg(response.message || '发送验证码失败');
                messageApi.open({
                    type: 'error',
                    content: response.message || '发送验证码失败',
                });
            }
        } catch (error) {
            setErrorMsg('发送验证码失败');
            messageApi.open({
                type: 'error',
                content: '发送验证码失败',
            });
        }
    };

    const handlePhoneClick = async () => {
        if (!phone) {
            setPhoneError('请输入手机号');
            return;
        }

        if (!validatePhone(phone)) {
            setPhoneError('请输入正确的手机号');
            return;
        }

        if (!code) {
            messageApi.open({
                type: 'error',
                content: '请输入验证码',
            });
            return;
        }

        if (!isAgreed) {
            messageApi.open({
                type: 'error',
                content: '请阅读并同意用户协议和隐私政策',
            });
            return;
        }

        try {
            // 验证短信验证码
            const verifyResult = await verifySmsCode(phone, code);
            
            if (verifyResult.success) {
                messageApi.open({
                    type: 'success',
                    content: '登录成功',
                });
                // 登录成功后跳转
                setTimeout(() => {
                    navigate("/tabber/first");
                }, 500);
            } else {
                messageApi.open({
                    type: 'error',
                    content: verifyResult.message || '验证码错误',
                });
            }
        } catch (error) {
            messageApi.open({
                type: 'error',
                content: '登录失败，请稍后重试',
            });
        }
    };

    const handleLogin = async () => {
        // e.preventDefault();
        if (bool) {
            if (isAgreed) {
                let result = await axios.post("http://localhost:3010/login", form)
                
                if (result.data.code == 200) {
                    localStorage.setItem("id",result.data.user._id)
                    messageApi.open({
                        // type: 'success',
                        content: '登录成功',
                    });
                    sessionStorage.setItem('accessToken',result.data.data.accessToken)
                    
                    setTimeout(()=>{
                        sessionStorage.removeItem('accessToken')
                    },5000)
                    setTimeout(()=>{
                        sessionStorage.setItem('refreshToken',result.data.data.refreshToken)
                        sessionStorage.setItem('accessToken',result.data.data.accessToken)
                    },5000)
                    setTimeout(() => {
                        navigate("/tabber/first")
                    }, 500)
                } else {
                    messageApi.open({
                        type: 'error',
                        content: '登录失败',
                    });
                }
            } else {
                messageApi.open({
                    type: 'error',
                    content: '请勾选下方协议',
                });
            }
        }else{
            setCaptchaVisible(true);
            console.log(bool);
            
        }

    }
    const [visibleFace, setVisibleFace] = useState(false)
    const [visibleSlider, setVisibleSlider] = useState(false)
    const [isLogin, setIsLogin] = useState(false)
    const handleClose2 = (bool) => {
        if (bool) {
            setTimeout(() => {
                setVisibleSlider(false)
                setBool(bool)
            }, 500)
        }
    }
    const handleClose = () => {
        setVisibleFace(false)
        setIsshow("用户名密码登录")
    }
    const handleOpen = () => {
        setVisibleFace(true)
    }
    const handleSliderOpen = () => {
        setVisibleSlider(true)
    }
    const [captchaVisible, setCaptchaVisible] = useState(false);    //控制滑块显示/隐藏
    return (
        <React.Fragment>
            {contextHolder}
            <div className={style['ljl-bigbox']}>
                <div className={style['ljl-bigbox-top']}>
                    <div className={style['ljl-bigbox-top-logo']}>LOGO</div>
                </div>
                <div className={style['ljl-bigbox-center']}>
                    <h4 className={style['ljl-bigbox-center-font']}>Hi~</h4>
                    <div style={{ display: isshow == "用户名密码登录" ? "block" : "none" }}>
                        <div className={style['input-container']}>
                            <div className={style['input-label']}>用户名</div>
                            <div className={style['phone-input-group']}>
                                <Input
                                    type="text"
                                    style={{ fontSize: "0.2rem" }}
                                    className={style['phone-input']}
                                    placeholder="请输入用户名"
                                    value={form.username}
                                    onChange={(e) => {
                                        setForm(prev => ({ ...prev, username: e }))
                                    }}
                                />
                            </div>
                            <div style={{ display: form.username ? "block" : "none" }}>
                                {form.username.length >= 5 && form.username.length <= 16 ? "" : <div style={{ fontSize: "0.3rem", color: "red" }}>{rule}</div>}
                            </div>
                        </div>
                        {/* 用户名须为5-16位数字和字母 */}

                        <div className={style['input-container']}>
                            <div className={style['input-label']}>密码</div>
                            <div className={style['code-input-group']}>
                                <Input
                                    type="text"
                                    className={style['code-input']}
                                    placeholder="请输入密码"
                                    value={form.password}
                                    onChange={(e) => {
                                        setForm(prev => ({ ...prev, password: e }))
                                    }}
                                // maxLength={6}
                                />

                            </div>
                        </div>
                        <div className={style['agreement-container']}>
                            <div style={{ width: "57%", display: "flex" }}>
                                <div className={style['checkbox-wrapper']} onClick={() => setIsAgreed(!isAgreed)}>
                                    <div className={`${style['checkbox']} ${isAgreed ? style['checked'] : ''}`}>
                                        {isAgreed && (
                                            <svg ref={selectRef} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="16" height="16">
                                                <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" />
                                            </svg>
                                        )}
                                    </div>
                                </div>
                                <div className={style['agreement-text']}>
                                    <span>我已阅读并同意</span><span className={style['link']}>《用户协议》</span>和<span className={style['link']}>《隐私政策》</span>
                                </div>
                            </div>
                            <div style={{ width: "37%", fontSize: "0.1rem", margin: "auto", display: "flex", justifyContent: "right", textAlign: "right" }}>
                                <div className={style['ljl-regiaterPhone']} onClick={() => { setIsshow("手机号登录") }} >手机号登录</div>
                                <div className={style['ljl-regiaterPhone']} onClick={() => { setIsshow("人脸识别登录") & handleOpen() }}>人脸识别登录</div>
                            </div>
                        </div>


                        <button className={style['register-button']} onClick={handleLogin}>
                            登录
                        </button>
                    </div>
                    {/* 手机号登录 */}
                    <div style={{ display: isshow == "手机号登录" ? "block" : "none" }}>
                        <div className={style['input-container']} >
                            <div className={style['input-label']}>手机号码</div>
                            <div className={style['phone-input-group']}>
                                <div className={style['country-code']}>+86</div>
                                <Input
                                    type="text"
                                    className={style['phone-input']}
                                    placeholder="请输入手机号"
                                    value={phone}
                                    onChange={(e) => {
                                        setPhone(e);
                                        if (phoneError) setPhoneError('');
                                    }}
                                    maxLength={11}
                                />
                            </div>
                            {phoneError && <div className={style['error-message']}>{phoneError}</div>}
                        </div>
                        <div className={style['input-container']}>
                            <div className={style['input-label']}>验证码</div>
                            <div className={style['code-input-group']}>
                                <Input
                                    type="text"
                                    className={style['code-input']}
                                    placeholder="请输入验证码"
                                    value={code}
                                    onChange={(e) => setCode(e)}
                                // maxLength={6}
                                />
                                <button
                                    className={`${style['send-code-button']} ${countdown > 0 ? style['disabled'] : ''}`}
                                    onClick={handleSendCode}
                                    disabled={countdown > 0}
                                >
                                    {countdown > 0 ? `重新发送(${countdown}s)` : '获取验证码'}
                                </button>
                            </div>
                        </div>




                        <div className={style['agreement-container']}>
                            <div style={{ display: "flex", width: "57%" }}>
                                <div className={style['checkbox-wrapper']} onClick={() => setIsAgreed(!isAgreed)}>
                                    <div className={`${style['checkbox']} ${isAgreed ? style['checked'] : ''}`}>
                                        {isAgreed && (
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="16" height="16">
                                                <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" />
                                            </svg>
                                        )}
                                    </div>
                                </div>
                                <div className={style['agreement-text']}>
                                    <span>我已阅读并同意</span> <span className={style['link']}>《用户协议》</span>和<span className={style['link']}>《隐私政策》</span>
                                </div>
                            </div>
                            <div style={{ width: "42%", margin: "auto", display: "flex", justifyContent: "center", textAlign: "right" }}>
                                <div className={style['ljl-regiaterPhone']} onClick={() => { setIsshow("用户名密码登录") }}>用户名密码登录</div>
                                <div className={style['ljl-regiaterPhone']} onClick={() => { setIsshow("人脸识别登录" & handleOpen()) }}>人脸识别登录</div>
                            </div>
                        </div>


                        <button className={style['register-button']} onClick={handlePhoneClick}>
                            登录
                        </button>
                    </div>


                </div>
                <div>
                    <Popup visible={visibleFace} style={{ width: "100%", height: "100%" }} onClose={() => setVisibleFace(false)}>
                        <Face handleClose={handleClose}></Face>
                    </Popup>
                    <Popup visible={visibleSlider} style={{ width: "100%", height: "35%" }} onClose={() => setVisibleSlider(false)}>
                        {/* <Slider1 bool={true} handleClose={handleClose2}></Slider1> */}
                    </Popup>
                </div>
                {captchaVisible
                    && (
                        <div style={{
                            position: 'fixed',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            background: 'rgba(0,0,0,0.5)',
                            zIndex: 1000,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}>
                            <div style={{
                                background: 'white',
                                padding: 20,
                                borderRadius: 8,
                                width: '90%',
                                maxWidth: 350
                            }}>
                                {/* <SliderCaptcha
                              request={getCaptcha}
                              onVerify={verifyCaptcha}
                             
                
                            /> */}


                                <SliderCaptcha
                                    request={getCaptcha}
                                    onVerify={(data) => {
                                        return verifyCaptcha(data)
                                            .then((result) => {
                                                setCaptchaVisible(false); // 验证成功直接关闭弹窗
                                                return result;           // 返回结果给组件
                                            })
                                            .catch((error) => {
                                                message.error(error.message); // 显示错误信息
                                                throw error;                 // 重新抛出错误，避免静默失败
                                            });
                                    }}
                                />


                                <Button
                                    block
                                    style={{ marginTop: 16 }}
                                    onClick={() => setCaptchaVisible(false)}
                                >
                                    取消
                                </Button>
                            </div>
                        </div>

                    )}
            </div>
        </React.Fragment>
    )
}

export default Register